package net.pws.common.event;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ApplicationEventBus {
    
    private static Log logger = LogFactory.getLog(ApplicationEventBus.class);
    
    protected static class SingletonHolder {
        static ApplicationEventBus instance = new ApplicationEventBus();
    }
    
    public static ApplicationEventBus getInstance() {
        return SingletonHolder.instance;
    }
    
    private List<ApplicationEventListener> listenerLists = new CopyOnWriteArrayList<ApplicationEventListener>();
    
    public ApplicationEventBus() {
        
    }
    
    public void addListener(ApplicationEventListener listener) {
        listenerLists.add(listener);
    }
    
    public void removeListener(ApplicationEventListener listener) {
        listenerLists.remove(listener);
    }
    
    public void publishEvent(ApplicationEventObject eventObject) {
        for (ApplicationEventListener listener : listenerLists) {
            try {
                if (listener.support(eventObject)) {
                    listener.handle(eventObject);
                }
            }
            catch (Exception e) {
                logger.error("handle event error.", e);
            }
        }
    }
}
